{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "initial_id",
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    ""
   ]
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 1、ConversationTokenBufferMemory的使用\n",
    "\n",
    "举例1："
   ],
   "id": "bb4d0858773b69df"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-03T11:51:54.985453Z",
     "start_time": "2025-09-03T11:51:54.526440Z"
    }
   },
   "cell_type": "code",
   "source": [
    "\n",
    "import os\n",
    "import dotenv\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "dotenv.load_dotenv()\n",
    "\n",
    "os.environ['OPENAI_API_KEY'] = os.getenv(\"OPENAI_API_KEY1\")\n",
    "os.environ['OPENAI_BASE_URL'] = os.getenv(\"OPENAI_BASE_URL\")\n",
    "\n",
    "# 创建大模型实例\n",
    "llm = ChatOpenAI(model=\"gpt-4o-mini\")"
   ],
   "id": "33743297522549d9",
   "outputs": [],
   "execution_count": 2
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-02T15:13:24.242827Z",
     "start_time": "2025-09-02T15:13:23.988655Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 1.导入相关包\n",
    "from langchain.memory import ConversationTokenBufferMemory\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "# 2.创建大模型\n",
    "llm = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "# 3.定义ConversationTokenBufferMemory对象\n",
    "memory = ConversationTokenBufferMemory(\n",
    "    llm=llm,\n",
    "    max_token_limit=10  # 设置token上限，默认值为2000\n",
    ")\n",
    "\n",
    "# 添加对话\n",
    "memory.save_context({\"input\": \"你好吗？\"}, {\"output\": \"我很好，谢谢！\"})\n",
    "memory.save_context({\"input\": \"今天天气如何？\"}, {\"output\": \"晴天，25度\"})\n",
    "\n",
    "# 查看当前记忆\n",
    "print(memory.load_memory_variables({}))"
   ],
   "id": "8adfe8fb21bca589",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'history': ''}\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\shkst\\AppData\\Local\\Temp\\ipykernel_33088\\3032367930.py:9: LangChainDeprecationWarning: Please see the migration guide at: https://python.langchain.com/docs/versions/migrating_memory/\n",
      "  memory = ConversationTokenBufferMemory(\n"
     ]
    }
   ],
   "execution_count": 3
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例2：",
   "id": "6068ec106361659e"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-02T15:14:56.446033Z",
     "start_time": "2025-09-02T15:14:56.390996Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 1.导入相关包\n",
    "from langchain.memory import ConversationTokenBufferMemory\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "# 2.创建大模型\n",
    "llm = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "# 3.定义ConversationTokenBufferMemory对象\n",
    "memory = ConversationTokenBufferMemory(\n",
    "    llm=llm,\n",
    "    max_token_limit=20  # 设置token上限，默认值为2000\n",
    ")\n",
    "\n",
    "# 添加对话\n",
    "memory.save_context({\"input\": \"你好吗？\"}, {\"output\": \"我很好，谢谢！\"})\n",
    "memory.save_context({\"input\": \"今天天气如何？\"}, {\"output\": \"晴天，25度\"})\n",
    "\n",
    "# 查看当前记忆\n",
    "print(memory.load_memory_variables({}))"
   ],
   "id": "f736e3e4f4bdcdf",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'history': 'AI: 晴天，25度'}\n"
     ]
    }
   ],
   "execution_count": 7
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 2、ConversationSummaryMemory的使用\n",
    "\n",
    "举例1：\n",
    "\n",
    "如果实例化ConversationSummaryMemory前，没有历史消息，可以使用构造方法实例化"
   ],
   "id": "ffb3c227fdaa1ff5"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-02T15:24:42.281467Z",
     "start_time": "2025-09-02T15:24:37.335545Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 1.导入相关包\n",
    "from langchain.memory import ConversationSummaryMemory, ChatMessageHistory\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "# 2.创建大模型\n",
    "llm = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "# 3.定义ConversationSummaryMemory对象\n",
    "memory = ConversationSummaryMemory(llm=llm)\n",
    "\n",
    "# 4.存储消息\n",
    "memory.save_context({\"input\": \"你好\"}, {\"output\": \"怎么了\"})\n",
    "memory.save_context({\"input\": \"你是谁\"}, {\"output\": \"我是AI助手小智\"})\n",
    "memory.save_context({\"input\": \"初次对话，你能介绍一下你自己吗？\"}, {\"output\": \"当然可以了。我是一个无所不能的小智。\"})\n",
    "\n",
    "# 5.读取消息（总结后的）\n",
    "print(memory.load_memory_variables({}))"
   ],
   "id": "16f7cebc92a59b4b",
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\shkst\\AppData\\Local\\Temp\\ipykernel_33088\\408448821.py:9: LangChainDeprecationWarning: Please see the migration guide at: https://python.langchain.com/docs/versions/migrating_memory/\n",
      "  memory = ConversationSummaryMemory(llm=llm)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'history': 'The human greets the AI with \"你好\" (hello), and the AI responds with \"怎么了\" (what\\'s wrong?). The human then asks, \"你是谁\" (who are you?), to which the AI replies, \"我是AI助手小智\" (I am the AI assistant Xiao Zhi). The human requests an introduction, and the AI states, \"当然可以了。我是一个无所不能的小智\" (Of course, I am an all-powerful Xiao Zhi).'}\n"
     ]
    }
   ],
   "execution_count": 8
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例2：如果实例化ConversationSummaryMemory前，已经有历史消息，可以调用from_messages()实例化",
   "id": "c09dd3de87b435e4"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-02T15:30:23.700155Z",
     "start_time": "2025-09-02T15:30:20.464765Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 1.导入相关包\n",
    "from langchain.memory import ConversationSummaryMemory, ChatMessageHistory\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "# 2.定义ChatMessageHistory对象\n",
    "llm = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "# 3.假设原始消息\n",
    "history = ChatMessageHistory()\n",
    "history.add_user_message(\"你好，你是谁？\")\n",
    "history.add_ai_message(\"我是AI助手小智\")\n",
    "\n",
    "# 4.创建ConversationSummaryMemory的实例\n",
    "memory = ConversationSummaryMemory.from_messages(\n",
    "    llm = llm,\n",
    "    #是生成摘要的原材料 保留完整对话供必要时回溯。当新增对话时，LLM需要结合原始历史生成新摘要\n",
    "    chat_memory = history,\n",
    ")\n",
    "\n",
    "print(memory.load_memory_variables({}))\n",
    "\n",
    "\n",
    "memory.save_context(inputs={\"human\":\"我的名字叫小明\"},outputs={\"ai\":\"很高兴认识你\"})\n",
    "\n",
    "print(memory.load_memory_variables({}))\n",
    "\n",
    "#记录了历史的交互的消息\n",
    "print(memory.chat_memory.messages)\n"
   ],
   "id": "fda83857d9c213d5",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'history': 'The human greets the AI and asks who it is. The AI responds that it is an AI assistant named Xiao Zhi.'}\n",
      "{'history': 'The human greets the AI, asks who it is, and introduces himself as Xiao Ming. The AI responds that it is an AI assistant named Xiao Zhi and expresses pleasure in meeting him.'}\n",
      "[HumanMessage(content='你好，你是谁？', additional_kwargs={}, response_metadata={}), AIMessage(content='我是AI助手小智', additional_kwargs={}, response_metadata={}), HumanMessage(content='我的名字叫小明', additional_kwargs={}, response_metadata={}), AIMessage(content='很高兴认识你', additional_kwargs={}, response_metadata={})]\n"
     ]
    }
   ],
   "execution_count": 12
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 3、ConversationSummaryBufferMemory的使用\n",
    "\n",
    "举例1："
   ],
   "id": "843b7b9f73f8e14"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-03T12:14:14.348834Z",
     "start_time": "2025-09-03T12:14:10.843442Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain.memory import ConversationSummaryBufferMemory\n",
    "\n",
    "# 获取大模型\n",
    "llm = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "# 实例化ConversationSummaryBufferMemory\n",
    "memory = ConversationSummaryBufferMemory(\n",
    "    llm = llm,\n",
    "    max_token_limit=40,  #控制缓冲区的大小\n",
    "    return_messages=True,\n",
    ")\n",
    "\n",
    "# 向memory中存储信息\n",
    "memory.save_context(inputs={\"input\":\"你好，我的名字叫小明\"},outputs={\"output\":\"很高兴认识你\"})\n",
    "memory.save_context(inputs={\"input\":\"李白是哪个朝代的诗人\"},outputs={\"output\":\"李白是唐朝的诗人\"})\n",
    "memory.save_context(inputs={\"input\":\"唐宋八大家里有苏轼吗？\"},outputs={\"output\":\"有\"})\n",
    "\n",
    "print(memory.load_memory_variables({}))\n",
    "\n",
    "print(\"\\n\")\n",
    "\n",
    "print(memory.chat_memory.messages)"
   ],
   "id": "fb33209e85864c04",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'history': [SystemMessage(content='The human introduces themselves as 小明. The AI expresses happiness to meet them. The human asks which dynasty the poet Li Bai belongs to.', additional_kwargs={}, response_metadata={}), AIMessage(content='李白是唐朝的诗人', additional_kwargs={}, response_metadata={}), HumanMessage(content='唐宋八大家里有苏轼吗？', additional_kwargs={}, response_metadata={}), AIMessage(content='有', additional_kwargs={}, response_metadata={})]}\n",
      "\n",
      "\n",
      "[AIMessage(content='李白是唐朝的诗人', additional_kwargs={}, response_metadata={}), HumanMessage(content='唐宋八大家里有苏轼吗？', additional_kwargs={}, response_metadata={}), AIMessage(content='有', additional_kwargs={}, response_metadata={})]\n"
     ]
    }
   ],
   "execution_count": 12
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "对比组：\n",
   "id": "64385776407f2d06"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-03T12:14:58.509825Z",
     "start_time": "2025-09-03T12:14:58.452283Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain.memory import ConversationSummaryBufferMemory\n",
    "\n",
    "# 获取大模型\n",
    "llm = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "# 实例化ConversationSummaryBufferMemory\n",
    "memory = ConversationSummaryBufferMemory(\n",
    "    llm = llm,\n",
    "    max_token_limit=100,  #控制缓冲区的大小\n",
    "    return_messages=True,\n",
    ")\n",
    "\n",
    "# 向memory中存储信息\n",
    "memory.save_context(inputs={\"input\":\"你好，我的名字叫小明\"},outputs={\"output\":\"很高兴认识你\"})\n",
    "memory.save_context(inputs={\"input\":\"李白是哪个朝代的诗人\"},outputs={\"output\":\"李白是唐朝的诗人\"})\n",
    "memory.save_context(inputs={\"input\":\"唐宋八大家里有苏轼吗？\"},outputs={\"output\":\"有\"})\n",
    "\n",
    "print(memory.load_memory_variables({}))\n",
    "\n",
    "print(\"\\n\")\n",
    "\n",
    "print(memory.chat_memory.messages)"
   ],
   "id": "6ef96caf664d0405",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'history': [HumanMessage(content='你好，我的名字叫小明', additional_kwargs={}, response_metadata={}), AIMessage(content='很高兴认识你', additional_kwargs={}, response_metadata={}), HumanMessage(content='李白是哪个朝代的诗人', additional_kwargs={}, response_metadata={}), AIMessage(content='李白是唐朝的诗人', additional_kwargs={}, response_metadata={}), HumanMessage(content='唐宋八大家里有苏轼吗？', additional_kwargs={}, response_metadata={}), AIMessage(content='有', additional_kwargs={}, response_metadata={})]}\n",
      "\n",
      "\n",
      "[HumanMessage(content='你好，我的名字叫小明', additional_kwargs={}, response_metadata={}), AIMessage(content='很高兴认识你', additional_kwargs={}, response_metadata={}), HumanMessage(content='李白是哪个朝代的诗人', additional_kwargs={}, response_metadata={}), AIMessage(content='李白是唐朝的诗人', additional_kwargs={}, response_metadata={}), HumanMessage(content='唐宋八大家里有苏轼吗？', additional_kwargs={}, response_metadata={}), AIMessage(content='有', additional_kwargs={}, response_metadata={})]\n"
     ]
    }
   ],
   "execution_count": 13
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例2：模拟客服交互",
   "id": "e186651b67e2ffa2"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-03T12:20:16.328193Z",
     "start_time": "2025-09-03T12:20:06.159526Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain.memory import ConversationSummaryBufferMemory\n",
    "from langchain_openai import ChatOpenAI\n",
    "from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder\n",
    "from langchain.chains.llm import LLMChain\n",
    "\n",
    "# 1、初始化大语言模型\n",
    "llm = ChatOpenAI(\n",
    "    model=\"gpt-4o-mini\",\n",
    "    temperature=0.5,\n",
    "    max_tokens=500\n",
    ")\n",
    "\n",
    "# 2、定义提示模板\n",
    "prompt = ChatPromptTemplate.from_messages([\n",
    "    (\"system\", \"你是电商客服助手，用中文友好回复用户问题。保持专业但亲切的语气。\"),\n",
    "    MessagesPlaceholder(variable_name=\"chat_history\"),\n",
    "    (\"human\", \"{input}\")\n",
    "])\n",
    "\n",
    "\n",
    "# 3、创建带摘要缓冲的记忆系统\n",
    "memory = ConversationSummaryBufferMemory(\n",
    "    llm=llm,\n",
    "    max_token_limit=400,\n",
    "    memory_key=\"chat_history\",\n",
    "    return_messages=True\n",
    ")\n",
    "\n",
    "# 4、创建对话链\n",
    "chain = LLMChain(\n",
    "    llm=llm,\n",
    "    prompt=prompt,\n",
    "    memory=memory,\n",
    ")\n",
    "\n",
    "# 5、模拟多轮对话\n",
    "dialogue = [\n",
    "    (\"你好，我想查询订单12345的状态\", None),\n",
    "    (\"这个订单是上周五下的\", None),\n",
    "    (\"我现在急着用，能加急处理吗\", None),\n",
    "    (\"等等，我可能记错订单号了，应该是12346\", None),\n",
    "    (\"对了，你们退货政策是怎样的\", None)\n",
    "]\n",
    "\n",
    "# 6、执行对话\n",
    "for user_input, _ in dialogue:\n",
    "    response = chain.invoke({\"input\": user_input})\n",
    "    print(f\"用户: {user_input}\")\n",
    "    print(f\"客服: {response['text']}\\n\")\n",
    "\n",
    "# 7、查看当前记忆状态\n",
    "print(\"\\n=== 当前记忆内容 ===\")\n",
    "print(memory.load_memory_variables({}))"
   ],
   "id": "6377c0e4d0956cd7",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "用户: 你好，我想查询订单12345的状态\n",
      "客服: 您好！感谢您的咨询。关于订单12345的状态，我会尽快为您查询。请稍等片刻。 \n",
      "\n",
      "（如果您需要更详细的信息，请提供订单相关的联系方式或其他信息，以便我更好地为您服务。）\n",
      "\n",
      "用户: 这个订单是上周五下的\n",
      "客服: 谢谢您提供的信息！我会尽快帮您查询上周五下的订单12345的状态。请稍等片刻。\n",
      "\n",
      "（如果您有其他问题或需要进一步的帮助，请随时告诉我！）\n",
      "\n",
      "用户: 我现在急着用，能加急处理吗\n",
      "客服: 我理解您的着急心情！关于加急处理订单的请求，通常需要联系配送部门进行确认。请您提供一下您的联系方式，我会尽快将您的请求反馈给相关部门，争取为您加急处理。\n",
      "\n",
      "如果您有其他问题或需要进一步的帮助，请随时告诉我！\n",
      "\n",
      "用户: 等等，我可能记错订单号了，应该是12346\n",
      "客服: 没问题，感谢您更新订单号！我将立即为您查询订单12346的状态。请稍等片刻。\n",
      "\n",
      "如果您还有其他问题或需要进一步的帮助，请随时告诉我！\n",
      "\n",
      "用户: 对了，你们退货政策是怎样的\n",
      "客服: 我们的退货政策如下：\n",
      "\n",
      "1. **退货期限**：一般情况下，您可以在收到商品后的7天内申请退货。\n",
      "2. **退货条件**：商品必须保持未使用状态，包装完整，附带原始标签和发票。\n",
      "3. **退货流程**：请您先联系客服申请退货，提供订单号和退货原因，我们会为您生成退货申请并提供相应的退货地址。\n",
      "4. **退款方式**：退货商品确认无误后，我们会在3-5个工作日内处理退款，退款将按照您原支付方式返还。\n",
      "\n",
      "如果您有具体的商品需要退货或者其他相关问题，请告诉我，我会尽力为您提供帮助！\n",
      "\n",
      "\n",
      "=== 当前记忆内容 ===\n",
      "{'chat_history': [SystemMessage(content='The human inquires about the status of order 12345. The AI responds by thanking the human for their inquiry and states that it will quickly check the status of the order, asking the human to wait a moment. The AI also offers to assist further if the human provides additional contact or order-related information.', additional_kwargs={}, response_metadata={}), HumanMessage(content='这个订单是上周五下的', additional_kwargs={}, response_metadata={}), AIMessage(content='谢谢您提供的信息！我会尽快帮您查询上周五下的订单12345的状态。请稍等片刻。\\n\\n（如果您有其他问题或需要进一步的帮助，请随时告诉我！）', additional_kwargs={}, response_metadata={}), HumanMessage(content='我现在急着用，能加急处理吗', additional_kwargs={}, response_metadata={}), AIMessage(content='我理解您的着急心情！关于加急处理订单的请求，通常需要联系配送部门进行确认。请您提供一下您的联系方式，我会尽快将您的请求反馈给相关部门，争取为您加急处理。\\n\\n如果您有其他问题或需要进一步的帮助，请随时告诉我！', additional_kwargs={}, response_metadata={}), HumanMessage(content='等等，我可能记错订单号了，应该是12346', additional_kwargs={}, response_metadata={}), AIMessage(content='没问题，感谢您更新订单号！我将立即为您查询订单12346的状态。请稍等片刻。\\n\\n如果您还有其他问题或需要进一步的帮助，请随时告诉我！', additional_kwargs={}, response_metadata={}), HumanMessage(content='对了，你们退货政策是怎样的', additional_kwargs={}, response_metadata={}), AIMessage(content='我们的退货政策如下：\\n\\n1. **退货期限**：一般情况下，您可以在收到商品后的7天内申请退货。\\n2. **退货条件**：商品必须保持未使用状态，包装完整，附带原始标签和发票。\\n3. **退货流程**：请您先联系客服申请退货，提供订单号和退货原因，我们会为您生成退货申请并提供相应的退货地址。\\n4. **退款方式**：退货商品确认无误后，我们会在3-5个工作日内处理退款，退款将按照您原支付方式返还。\\n\\n如果您有具体的商品需要退货或者其他相关问题，请告诉我，我会尽力为您提供帮助！', additional_kwargs={}, response_metadata={})]}\n"
     ]
    }
   ],
   "execution_count": 15
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "# 4、ConversationEntityMemory的使用（了解）",
   "id": "1b80d48cb46eb80d"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-03T13:18:22.808396Z",
     "start_time": "2025-09-03T13:18:09.814696Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain.chains.conversation.base import LLMChain\n",
    "from langchain.memory import ConversationEntityMemory\n",
    "from langchain.memory.prompt import ENTITY_MEMORY_CONVERSATION_TEMPLATE\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "# 初始化大语言模型\n",
    "llm = ChatOpenAI(model_name='gpt-4o-mini', temperature=0)\n",
    "# 使用LangChain为实体记忆设计的预定义模板\n",
    "prompt = ENTITY_MEMORY_CONVERSATION_TEMPLATE\n",
    "# 初始化实体记忆\n",
    "memory = ConversationEntityMemory(llm=llm)\n",
    "# 提供对话链\n",
    "chain = LLMChain(\n",
    "    llm=llm,\n",
    "    prompt=ENTITY_MEMORY_CONVERSATION_TEMPLATE,\n",
    "    memory=ConversationEntityMemory(llm=llm),\n",
    "    #verbose=True,  # 设置为True可以看到链的详细推理过程\n",
    ")\n",
    "\n",
    "# 进行几轮对话，记忆组件会在后台自动提取和存储实体信息\n",
    "chain.invoke(input=\"你好，我叫蜘蛛侠。我的好朋友包括钢铁侠、美国队长和绿巨人。\")\n",
    "chain.invoke(input=\"我住在纽约。\")\n",
    "chain.invoke(input=\"我使用的装备是由斯塔克工业提供的。\")\n",
    "\n",
    "# 查询记忆体中存储的实体信息\n",
    "print(\"\\n当前存储的实体信息:\")\n",
    "print(chain.memory.entity_store.store)\n",
    "\n"
   ],
   "id": "6ebb2d01576c2869",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "当前存储的实体信息:\n",
      "{'蜘蛛侠': '蜘蛛侠的好朋友包括钢铁侠、美国队长和绿巨人。', '钢铁侠': '钢铁侠是蜘蛛侠的好朋友之一。', '美国队长': '美国队长是蜘蛛侠的好朋友之一。', '绿巨人': '绿巨人是蜘蛛侠的好朋友之一。', '纽约': '蜘蛛侠住在纽约。', '斯塔克工业': '斯塔克工业提供了蜘蛛侠使用的装备。'}\n"
     ]
    }
   ],
   "execution_count": 37
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-03T13:19:04.301386Z",
     "start_time": "2025-09-03T13:18:58.146112Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 基于记忆进行提问\n",
    "answer = chain.invoke(input=\"你能告诉我蜘蛛侠住在哪里以及他的好朋友有哪些吗？\")\n",
    "print(\"\\nAI的回答:\")\n",
    "print(answer)"
   ],
   "id": "3aa9eaff4306ae71",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "AI的回答:\n",
      "{'input': '你能告诉我蜘蛛侠住在哪里以及他的好朋友有哪些吗？', 'history': 'Human: 你好，我叫蜘蛛侠。我的好朋友包括钢铁侠、美国队长和绿巨人。\\nAI: 你好，蜘蛛侠！很高兴认识你。你和钢铁侠、美国队长以及绿巨人都是超级英雄，真是一个强大的团队！你们最近有什么冒险吗？\\nHuman: 我住在纽约。\\nAI: 纽约是一个充满活力的城市，适合超级英雄们活动！你在纽约的生活怎么样？有没有遇到什么有趣的事情或者挑战？\\nHuman: 我使用的装备是由斯塔克工业提供的。\\nAI: 斯塔克工业的装备真是太棒了！钢铁侠的技术总是让人惊叹。你最喜欢使用哪一件装备？它在你的冒险中帮助了你哪些方面？', 'entities': {'蜘蛛侠': '蜘蛛侠的好朋友包括钢铁侠、美国队长和绿巨人。', '纽约': '蜘蛛侠住在纽约。', '钢铁侠': '钢铁侠是蜘蛛侠的好朋友之一。', '美国队长': '美国队长是蜘蛛侠的好朋友之一。', '绿巨人': '绿巨人是蜘蛛侠的好朋友之一。'}, 'text': '蜘蛛侠住在纽约。他的好朋友包括钢铁侠、美国队长和绿巨人。这些超级英雄们常常一起合作，面对各种挑战和敌人。你对他们的冒险有什么特别的记忆吗？'}\n"
     ]
    }
   ],
   "execution_count": 38
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "# 5、ConversationKGMemory的使用（了解）\n",
   "id": "ca80cfd796354e3d"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-03T13:25:34.885482Z",
     "start_time": "2025-09-03T13:25:32.423142Z"
    }
   },
   "cell_type": "code",
   "source": [
    "#1.导入相关包\n",
    "from langchain.memory import ConversationKGMemory\n",
    "from langchain.chat_models import ChatOpenAI\n",
    "\n",
    "# 2.定义LLM\n",
    "llm = ChatOpenAI(model=\"gpt-4o-mini\", temperature=0)\n",
    "\n",
    "# 3.定义ConversationKGMemory对象\n",
    "memory = ConversationKGMemory(llm=llm)\n",
    "\n",
    "# 4.保存会话\n",
    "memory.save_context({\"input\": \"向山姆问好\"}, {\"output\": \"山姆是谁\"})\n",
    "memory.save_context({\"input\": \"山姆是我的朋友\"}, {\"output\": \"好的\"})\n",
    "\n",
    "# 5.查询会话\n",
    "memory.load_memory_variables({\"input\": \"山姆是谁\"})"
   ],
   "id": "b8db87a38a5141a2",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'history': 'On 山姆: 山姆 是 我的朋友.'}"
      ]
     },
     "execution_count": 40,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 40
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-03T13:26:06.292248Z",
     "start_time": "2025-09-03T13:26:04.610783Z"
    }
   },
   "cell_type": "code",
   "source": "memory.get_knowledge_triplets(\"她最喜欢的颜色是红色\")",
   "id": "7e2264a98f818c00",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[KnowledgeTriple(subject='山姆', predicate='是', object_='我的朋友'),\n",
       " KnowledgeTriple(subject='山姆', predicate='最喜欢的颜色是', object_='红色')]"
      ]
     },
     "execution_count": 41,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 41
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 6、VectorStoreRetrieverMemory的使用（了解）\n",
    "\n"
   ],
   "id": "565d1d6c0faf081a"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-09-03T13:52:17.454338Z",
     "start_time": "2025-09-03T13:52:16.166429Z"
    }
   },
   "cell_type": "code",
   "source": [
    "# 1.导入相关包\n",
    "from langchain_openai import OpenAIEmbeddings\n",
    "from langchain.memory import VectorStoreRetrieverMemory\n",
    "from langchain_community.vectorstores import FAISS\n",
    "from langchain.memory import ConversationBufferMemory\n",
    "\n",
    "# 2.定义ConversationBufferMemory对象\n",
    "memory = ConversationBufferMemory()\n",
    "memory.save_context({\"input\": \"我最喜欢的食物是披萨\"}, {\"output\": \"很高兴知道\"})\n",
    "memory.save_context({\"Human\": \"我喜欢的运动是跑步\"}, {\"AI\": \"好的,我知道了\"})\n",
    "memory.save_context({\"Human\": \"我最喜欢的运动是足球\"}, {\"AI\": \"好的,我知道了\"})\n",
    "\n",
    "# 3.定义向量嵌入模型\n",
    "embeddings_model = OpenAIEmbeddings(\n",
    "    model=\"text-embedding-ada-002\"\n",
    ")\n",
    "\n",
    "# 4.初始化向量数据库\n",
    "vectorstore = FAISS.from_texts(memory.buffer.split(\"\\n\"), embeddings_model)  # 空初始化\n",
    "\n",
    "# 5.定义检索对象\n",
    "retriever = vectorstore.as_retriever(search_kwargs=dict(k=1))\n",
    "\n",
    "# 6.初始化VectorStoreRetrieverMemory\n",
    "memory = VectorStoreRetrieverMemory(retriever=retriever)\n",
    "\n",
    "print(memory.load_memory_variables({\"prompt\": \"我最喜欢的食物是\"}))"
   ],
   "id": "35083f5aa2a7bb8e",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'history': 'Human: 我最喜欢的食物是披萨'}\n"
     ]
    }
   ],
   "execution_count": 43
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
